<?php
namespace App\Models;

use App\Models\ComModel;

/**
 * 后台必须模型
 */
class AdminModel extends ComModel
{

    public function __construct()
    {
        parent::__construct();
        $this->table = 'admin';
    }

    // 后台管理员登录
    public function login($username, $password, $remember = 0)
    {
        $user = $this->db->table($this->table)->where('username', $username)->where('status', 1)->where('unlock<' . time())->limit(1)->get()->getRowArray();

        // 判断用户状态
        if (!$user || (md5(sha1($password) . $user['salt'] . sha1($password)) != $user['password'])) {
            if ($user && defined('SITE_ADMIN_LOCK') && SITE_ADMIN_LOCK) {
                if ($user['islock'] >= SITE_ADMIN_LOCK) {
                    $rt['msg'] = SITE_ADMIN_LOCK . '次登录错误后,将锁定账号!';
                    $unlock = time() + SITE_ADMIN_LOCK_HOUR * 3600;
                    $this->db->table($this->table)->where('userid', $user['userid'])->update(['unlock' => $unlock]);
                    $unlock = date('Y-m-d', $unlock);
                    return ams_rt(1, '账号或IP可能已经锁定');
                } else {
                    $this->db->table($this->table)->where('userid', $user['userid'])->set('islock', 'islock+1', false)->update();
                }
            }
            return ams_rt(1, '账号或者密码错误');
        }
        $this->db->table($this->table)->where('userid', $user['userid'])->update(['islock' => 0, 'unlock' => 0]);

        $session = \Config\Services::session();

        //查询admin
        $admin = $user;

        // 查询此用户角色组
        $role = $this->_role($admin['roleid']);
        if (!$role) {
            return ams_rt(1, '角色不存在');
        }
        // 管理员登录日志记录
        $this->addLoginLog($user);
        // 保存会话
        $session->set('admin', $admin);

        $response = \Config\Services::response();
        $response->setCookie('adminid', $user['userid'], WEEK)->send();
        $response->setCookie('admin_cookie', md5(SITE_KEY . $user['password']), WEEK)->send();
        return ams_rt(0, '登录成功', $user['userid']);
    }

    //安装时注册管理用户
    public function addRoot($username, $password, $email = '')
    {
        $data = [
            'username' => $username,
            'password' => $password,
            'email' => $email,
        ];
        $data['roleid'] = 1;
        $data['salt'] = $salt = ams_salt(); //10位
        $data['password'] = $password = md5(sha1($data['password']) . $salt . sha1($data['password']));
        $request = \Config\Services::request();
        $data['regip'] = $request->getIPAddress();
        $data['regtime'] = time();
        $data['status'] = 1;
        $this->db->table($this->table)->insert($data);
        $userid = $this->db->insertID();
        if ($userid) {
            return ams_rt(0, '操作成功');
        }
        $msg = $this->db->error();
        return ams_rt(1, '操作失败:' . ($msg['message'] ?? ''));
    }

    //退出
    public function logout()
    {
        $session = \Config\Services::session();
        $session->remove('admin');
        delete_cookie('adminid');
        delete_cookie('admin_cookie');
        return ams_rt(0, '退出成功');
    }

    public function get($userid)
    {
        $userid = intval($userid);
        $data = $this->db->table('admin')->where('userid', $userid)->get()->getRowArray();
        if ($data && $data['roleid']) {
            $data['role'] = $this->_role($data['roleid']);
        }
        return $data;
    }

    public function check_admin_cookie($admin)
    {
        $request = \Config\Services::request();
        $cookie = get_cookie('admin_cookie');
        if (!$cookie) {
            return 0;
        } elseif (md5(SITE_KEY . $admin['password']) !== $cookie) {
            return 0;
        }
        return 1;
    }

    // 获取当前管理员的角色组id
    private function _role($role_id)
    {
        $role = $this->db->table('rbac_role')->where('id', $role_id)->where('status', 1)->get()->getResultArray();
        if (!$role) {
            return false;
        }
        return $role;
    }

    /**
     * 登录记录
     */
    public function addLoginLog($user)
    {
        $request = \Config\Services::request();
        $ip = $request->getIPAddress();
        $agent = $request->getUserAgent();
        $data = [
            'userid' => $user['userid'] ?? 0,
            'loginip' => $ip ?? '',
            'logintime' => time(),
            'useragent' => substr($agent, 0, 250),
        ];
        // 同一天Ip一致时只更新一次更新时间 今天
        $row = $this->db->table($this->table . '_login')->where('userid', $user['userid'])->where('loginip', $ip)->where('DATEDIFF(from_unixtime(logintime),now())=0')->get()->getRowArray();
        if ($row) {
            $this->db->table($this->table . '_login')->where('id', $row['id'])->update($data);
        } else {
            $this->db->table($this->table . '_login')->insert($data);
        }

    }

}
